<?php
namespace app\index\controller;

use think\Controller;
use think\Response\Json;
use think\Request;
use think\Db;
use think\Session;
/**
* 前台首页
*/
class User extends Base
{	
	public function _initialize() {
		parent::_initialize();
	}

    public function index() {
        $this->auth();

        $request            = request();
        $params             = $request->param();
        $uid                = session('uid');
        $p                  = $request->has('p') ? $params['p'] : 1;
        $limit              = $request->has('limit') ? $params['limit'] : 8;
        $status             = $request->has('status') ? $params['status'] : null;
        
        $post               = session('post');

        if($post            == 0) {
            $map['uuid']    = $uid;
        } else {
            $map['uid']     = $uid;
            
        }

        if(empty($status)) {
            $map['status']  = array('lt', 3);
        } else {
            $map['status']  = array('eq', $status);
        }

        $count              = Db::name('repair')->where($map)->count();
        $order              = Db::name('repair')->where($map)->limit($p - 1, $limit)->order('id desc')->select();

        foreach ($order as $key => &$value) {
            $wx_uid             = $value['uid'];
            $bx_uid             = $value['uuid'];
            $value['wx_name']   = $this->get_user_config($wx_uid) . '(' . $this->get_user_config($wx_uid, 'truename') . ')';
            $value['bx_name']   = $this->get_user_config($bx_uid). '(' . $this->get_user_config($bx_uid, 'truename') . ')';
        }



        $this->assign('order', $order);
        return $this->fetch('User/index');
    }

	public function login(Request $request) {
		if($request->isPost()){
    		$data 			      = $request->post();
 	
    		$username 	          = $data['username'];
    		$password 		      = $data['password'];
    		$post 			      = $data['post'];
    		$map['a.username']    = $username;
            $map['b.post']        = $post > 0 ? array(array('neq', 0), array('neq', 999)) : array('eq', $post);

    		$user 			= Db::name('user a')->join('web_job b', 'a.uid=b.uid')->where($map)->find();



    		if(empty($username) || empty($password)) {
    			$this->error('账号密码不能为空');
    		}

    		if($user){
    			if(md5($password) == $user['password']) {
    				session('username', $user['username']);
                    session('post', $post);
                    session('uid', $user['uid']);
    				$this->redirect('/');
    			} else {
    				$this->error('密码错误');
    			}
    		} else {
    			$this->error('没有该用户');
    		}
			return;
		}
    	return $this->fetch('User/login');
	}

	public function logout() {
		Session::delete('username');
        Session::delete('post');
        Session::delete('uid');
		$this->success('退出成功', '/');
	}

    public function commit() {
        $this->auth();
        $id             = $this->request->get('id');
        $status         = 2;
        $time           = time();
        if(empty($id)) {
            $this->error('参数有误');
            exit;
        }

        $map['id']      = $id;

        $flag           = Db::name('repair')->where($map)->setField(array('status' => $status, 'a_hour' => $time));
        $uuname         = session('username');
        $mobile         = $this->get_user_config(session('uid'), 'mobile');

        if($flag) {
            $this->progress_trace(array(
                'status'        => $status,
                'repair_id'     => $id,
                'time'          => $time,
                'content'       => '受理人【' . $uuname . '】已经接受你的报修单,请耐心等待【' .$uuname. '】上门处理,联系方式为: ' . $mobile 
            ));
            $this->success('接受订单,请及时上门维修', '/User/index');
        } else {
            $this->error('服务器繁忙,稍后再试', '/User/index');
        }
    }

    public function complete() {
        $this->auth();

        $id             = $this->request->get('id');
        $status         = 3;
        $time           = time();
        if(empty($id)) {
            $this->error('参数有误');
            exit;
        }

        $map['id']      = $id;

        $flag           = Db::name('repair')->where($map)->setField(array('status' => $status, 'c_hour' => $time));

        if($flag) {
            $this->progress_trace(array(
                'status'        => $status,
                'repair_id'     => $id,
                'time'          => $time,
                'content'       => '处理完成,等待用户评价'
            ));
            $this->success('处理完成,等待用户评价', '/User/index');
        } else {
            $this->error('服务器繁忙,稍后再试', '/User/index');
        }
    }

    public function comment(Request $request) {
        if($request->isPost()) {
            $data           = $request->post();
            $status         = 4;
            $time           = time();
            $data['time']   = $time;
            $data['from']   = session('uid');
            if(!$data['to'] && !$data['from']) {
                $this->error('评价失败', 'User/index');
            }

            $res1               = Db::name('comment')->insertGetId($data);
            $res2               = Db::name('repair')->where(array('id' => $data['repair_id']))->setField(array('status' => $status));
            $this->progress_trace(array(
                'status'        => $status,
                'repair_id'     => $data['repair_id'],
                'time'          => $time,
                'content'       => $this->get_user_config(session('uid')).'('.$this->get_user_config(session('uid'), 'truename').')已经对你评价'
            ));



            if($res1 && $res2) {
                $this->success('评价成功', 'User/index');
            } else {
                $this->error('评价失败', 'User/index');
            }
        }
    }

	public function form(Request $request) {
        $JOB                = ['学生', '电器类', '木工', '电子信息类', '玻璃维修'];
        $this->auth();
        $time               = time();
        if($request->isPost()) {
            $data           = $request->post();
            $data['time']   = $time;
            $staff          = $this->getRand('job', array('post' => $data['repair_type']), $time);

            if($staff) {
                $status     = 1;
            } else {
                $status     = 0;
            }
            $data['status'] = $status;
            $data['uid']    = $staff['uid'];
            $data['uuid']   = session('uid');
            $data['c_hour'] = 0;
            $data['a_hour'] = 0;

            $flag           = Db::name('repair')->insertGetId($data);
            
            if(!$flag) {
                $this->error('报修失败');
            } else {

                $uuname         = $this->get_user_config($staff['uid']); // 受理人

                $this->progress_trace(array(
                    'repair_id' => $flag,
                    'time'      => $time,
                    'status'    => 0,
                    'content'   => '【' . session('username') . '】于' . date('Y-m-d H:i:s', $time) . '在网上申报维修' 
                ));

                $this->progress_trace(array(
                    'repair_id' => $flag,
                    'time'      => $time,
                    'status'    => 1,
                    'content'   => '系统自动将任务分配给【 '. $uuname .' 】 等待受理人【 '. $uuname .' 】【 '. $time .' 】进行受理。'
                ));

                $this->success('报修成功, 等待受理', 'User/index');
            }
        }
        $map['post']        = array(array('neq', 0), array('neq', 999)); //不等于学生
        $JOBS               = Db::name('job')->group('post')->where($map)->select();

        foreach ($JOBS as $key => &$value) {
            $value['post_name']  = $JOB[$value['post']];
        }
        $this->assign('jobs', $JOBS);
    	return $this->fetch('User/form');
	}

    public function getRand($table = '', $where = array(), $time) {
        if(empty($table)) return;
        $list           = Db::name('job')->where($where)->select();

        $count          = count($list);
        $rundnum        = floor(rand(0, $count - 1));


        if($list[$rundnum]) {
            $msg        = array(
                'to'    => $list[$rundnum]['uid'],
                'from'  => session('uid'),
                'time'  => $time,
                'status'=> 0,
                'title' => '维修通知',
                'content'=> '用户' . session('username') . '的订单交给你处理, 请确认'
            );
            Db::name('message')->insertGetId($msg);
            return $list[$rundnum];
        }
    }

    public function progress_trace($map) {
        return Db::name('progress')->insertGetId($map);
    }

    public function get_user_config($uid, $field = 'username') {
            $map['uid']     = $uid;
            return Db::name('user')->where($map)->find()[$field];
    }
}
